package com.qy.util;


import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 网关配置
 */
public class NetConfigUtil {

	private static Map<Integer, NetConfig> gameMap = new HashMap<Integer, NetConfig>();
	private static Map<Integer, NetConfig> redisMap = new HashMap<Integer, NetConfig>();
	private static Map<Integer, NetConfig> mainDBMap = new HashMap<Integer, NetConfig>();

	public static boolean init() {
		if (!initGlobal()) {
			return false;
		}

		return true;
	}

	private static boolean initGlobal() {
		try {
			String globalPath =ServerConfigUtil.getPath("global.path");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(globalPath);
			Element root = doc.getRootElement();
			
			Element game = root.element("game_server");
			init(game, "game", gameMap);
			
			Element redis = root.element("redis_server");
			init(redis, "redis", redisMap);
			
			Element mainDb = root.element("maindb_server");
			init(mainDb, "db", mainDBMap);
			
			return true;
		} catch (Exception e) {
			LogUtil.error("init global config file fialed., server start failed.", e);
			return false;
		}
	}

	private static void init(Element root, String nodeName, Map<Integer, NetConfig> map) {
		if (root == null) {
			return;
		}
		Iterator<?> itr = root.elementIterator(nodeName);
		while (itr.hasNext()) {
			Element element = (Element) itr.next();
			int id = Integer.valueOf(element.attributeValue("id"));
			String name = element.attributeValue("name");
			int port = Integer.valueOf(element.attributeValue("port"));
			int adminPort = 0;
			if (element.attributeValue("adminPort") != null) {
				adminPort = Integer.valueOf(element.attributeValue("adminPort"));
			}
			String address = element.attributeValue("address");
			String user = element.attributeValue("user");
			String password = element.attributeValue("password");
			NetConfig config = new NetConfig(id, name, address, port, adminPort, user, password);
			map.put(config.getId(), config);
			LogUtil.info("parse server config succ," + config);
		}
	}

	/**
	 * 服务器配置
	 * @param serverType
	 * @param serverId
	 * @return
	 */
	public static NetConfig getNetConfigXml(int serverType, int serverId) {
		NetConfig xml = null;
		switch (serverType) {
		case 1:
			xml = gameMap.get(serverId);
			break;
		case 2:
			xml = redisMap.get(serverId);
			break;
		case 3:
			xml = mainDBMap.get(serverId);
			break;
		}
		return xml;
	}

	/**
	 * 服务器配置
	 * 
	 * @param serverType
	 * @param serverId
	 * @return
	 */
	public static Collection<NetConfig> getNetConfigXml(int serverType) {
		Collection<NetConfig> xml = null;
		switch (serverType) {
		case 1:
			xml = gameMap.values();
			break;
		}
		return xml;
	}

}
